﻿using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ivory.Libs
{
    public class FrameTimeStats
    {
        private string InstanceName;

        //Fields
        public double MinFrameTimeMS { get; private set; }
        public double MaxFrameTimeMS { get; private set; }

        public double AverageFrameTimeMS { get; private set; }

        private IvoryLog _FrameTimeLogger;
        private DateTime _StartTime;
        private Queue<TimeSpan> _DateStack;

        //ctor
        public FrameTimeStats(string IN)
        {
            _DateStack = new Queue<TimeSpan>(10);
            InstanceName = IN;
            _FrameTimeLogger = new IvoryLog(string.Format("FRAMETIME_{0}.txt", DateTime.Now.ToString("hh_mm")));
            _FrameTimeLogger.ShowTimeStamp = false;
        }

        //Methods
        public void StartFrame()
        {
            _StartTime = DateTime.Now;
        }
        public void EndFrame(GameTime time)
        {
            //Time Difference since the Start Call
            TimeSpan frameTime = DateTime.Now.Subtract(_StartTime);
            //_FrameTimeLogger.Write(frameTime.TotalMilliseconds);

            //Increase & Calculate AverageFrameTime
            if (_DateStack.Count >= 10)
            {
                _DateStack.Dequeue();
                _DateStack.Enqueue(frameTime);
            }
            else
                _DateStack.Enqueue(frameTime);

            if (_DateStack.Count >= 1)
            {
                AverageFrameTimeMS = _DateStack.Average(f => f.TotalMilliseconds);
                //See if this is a new Min or Max Frame time
                MinFrameTimeMS = _DateStack.Min(f => f.TotalMilliseconds);
                MaxFrameTimeMS = _DateStack.Max(f => f.TotalMilliseconds);
            }
        }


        public override string ToString()
        {
            //FORMAT {MIN} << {AVG} << {MAX}
            return string.Format("{0:00.00}ms < {1:00.00}ms < {2:00.00}ms", Math.Round(MinFrameTimeMS, 2), Math.Round(AverageFrameTimeMS, 2), Math.Round(MaxFrameTimeMS, 2));
        }

    }
}
